package br.com.sgo.controller;

import java.util.List;

import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.sgo.dao.PatientDao;
import br.com.sgo.model.Patient;

@Resource
@Path("paciente")
public class PatientController {

	private final Result result;
	private final PatientDao patientDao;

	public PatientController(Result result, PatientDao patientDao) {
		this.result = result;
		this.patientDao = patientDao;
	}

	@Path("listar")
	public void list() {
		
		List<Patient> patients = patientDao.list();
		if(patients.size() > 0)
			result.include("patients", patients);
		else
			result.redirectTo(this).form();
		
	}

	@Path("alterar/{patient.id}")
	public void form(Patient patient) {
		patient = patientDao.load(patient);
		if(patient != null)
			result.include("patient", patient);
		else
			result.redirectTo(this).list();
	}
	
	@Path("cadastrar")
	public void form() {}
	
	@Path("salvar")
	public void save(Patient patient) {
		
		try {
			patientDao.save(patient);
			result.redirectTo(this).list();
		}
		catch(Exception e) {
			result.redirectTo(this).form(patient);
		}
	}
	
	@Path("excluir/{patient.id}")
	public void delete(Patient patient) {
		
		try {
			patientDao.delete(patient);			
		}
		catch(Exception e) {
			
		}
		result.redirectTo(this).list();
	}	
	
}
